package com.zqs.compareface.utils.impl;

import org.junit.Assert;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @Program: FaceCompares
 * @Description:
 * @Author: zqs
 * @Create： 2022-01-12-16:23
 */
public class ImageToJpgUtil {
    /**
     * 将{@link BufferedImage}生成formatName指定格式的图像数据
     * @param source
     * @param formatName 图像格式名，图像格式名错误则抛出异常
     * @return
     */
    public static byte[] wirteBytes(BufferedImage source, String formatName){
        //Assert.notNull(source, "source");  //spring中可用
        //Assert.notEmpty(formatName, "formatName");  //spring中可用
        Assert.assertNotNull(source); //junit工具中使用

        Objects.requireNonNull(source); //java项目中使用
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Graphics2D g = null;
        try {
            for(BufferedImage s=source;!ImageIO.write(s, formatName, output);){
                if(null!=g) {
                    throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName));
                }
                s = new BufferedImage(source.getWidth(),
                        source.getHeight(), BufferedImage.TYPE_INT_RGB);
                g = s.createGraphics();
                g.drawImage(source, 0, 0,null);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != g) {
                g.dispose();
            }
        }
        return output.toByteArray();
    }
}
